package springOllamaApi.api;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("ollama")
public class Ollama {

    @Autowired
    OllamaChatModel ollamaChatModel;

    @Autowired
    @Qualifier("ChatClientPoem")
    ChatClient chatClient;

    @RequestMapping(value = "poem", produces = "text/html;charset=utf-8")
    public Flux<String> poem(@RequestParam("msg") String msg) {
        return chatClient.prompt().user(msg).stream().content();
    }

    @RequestMapping("chat")
    public String chat(@RequestParam("msg") String msg) {
        System.out.println("chat 收到请求");
        return ollamaChatModel.call(msg);
    }

    @RequestMapping(value = "stream", produces = "text/html;charset=utf-8")
    public Flux<String> stream(@RequestParam("msg") String msg) {

        System.out.println("stream 收到请求");
        return ollamaChatModel.stream(msg);
    }

    @RequestMapping(value = "stream-memory", produces = "text/html;charset=utf-8")
    public Flux<String> memory(@RequestParam("msg") String msg, @RequestParam("chatId") String chatId) {
        System.out.println("stream 收到请求");
        return chatClient.prompt()
                .user(msg)
                .advisors(spec -> spec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream().content();
    }
}
